package com.kzw.web;

import java.awt.image.RenderedImage;
import java.io.IOException;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kzw.entity.User;
import com.kzw.service.UserService;
import com.kzw.utils.CodeUtil;

import my.bean.Msg;
import my.mvc.Annotation.JSON;
import my.mvc.RequestContext;

public class LoginAction {

	private UserService service = new UserService();
	
	/**
	 * 生成验证码
	 * */
	public void vcode(HttpServletRequest req, HttpServletResponse resp) {
		 // 调用工具类生成的验证码和验证码图片
        Map<String, Object> codeMap = CodeUtil.generateCodeAndPic();

        // 将四位数字的验证码保存到Session中。
        HttpSession session = req.getSession();
        session.setAttribute("code", codeMap.get("code").toString());

        // 禁止图像缓存。
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", -1);

        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中。
        ServletOutputStream sos;
        try {
            sos = resp.getOutputStream();
            ImageIO.write((RenderedImage) codeMap.get("codePic"), "jpeg", sos);
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
	}
	
	/**
	 * 登陆
	 * */
	@JSON
	public Msg index(RequestContext rc) {
		String uname = rc.param("uname");
		String passwd = rc.param("passwd");
		String code = rc.param("code");
		
		Msg msg = new Msg();
		String vcode = rc.sessionAttr("code")+"";
		if(!code.equalsIgnoreCase(vcode)) {
			msg.setSuccess(false);
			msg.setMsg("验证码错误！");
			return msg;
		}
		
		User user = service.validUser(uname, passwd);
		if(user == null) {
			msg.setSuccess(false);
			msg.setMsg("账号或密码不正确！");
		} else {
			rc.sessionAttr("USER", user);
		}		
		
		return msg;
	}
}
